package com.simba.server.commands.impl.web;

import java.util.*;

import com.google.gson.Gson;
import com.simba.common.command.ICommand;
import com.simba.common.utils.StringUtil;
import com.simba.server.base.CommonUtil;
import com.simba.server.base.TimeUtil;
import com.simba.server.components.MachineParams;
import com.simba.server.components.SlotManager;
import com.simba.server.components.SortCommonDefines;
import com.simba.server.components.SorterParams;
import com.simba.server.components.data.*;
import org.apache.log4j.Logger;

import com.simba.common.log.LogUtil;
import com.simba.server.ServerParam;
import com.simba.server.webservice.WebServiceManager;

public class WebPackSlotCmd implements ICommand
{
	public static final String NAME = "WebPackSlotCmd";
	private static final Logger logger = Logger.getLogger(WebPackSlotCmd.class);
	private final BoxInfo info;

	public WebPackSlotCmd(BoxInfo info)
	{
		this.info = info;
	}

	@Override
	public String getName()
	{
		return WebPackSlotCmd.NAME;
	}

	@Override
	public Boolean run(Object params)
	{
		boolean ret = false;
		String remoteMethod = "AutoSort/ChutePrint";

		Map<String,Object> rp = new HashMap<>();
		//自动生成
		rp.put("Guid", TimeUtil.getTimeDateString("yyMMddHHmmss", new Date())+CommonUtil.getRandom(1000000000L));
		//箱号
		rp.put("BoxCode", info.getBoxCode());
		//格口号
		rp.put("ChuteCode", CommonUtil.doNullData(info.getSlotId(), "0"));
		//分拣机代码
		rp.put("MachineCode", MachineParams.getInstance().getDeviceId());
		//请求时间
		rp.put("RequestTime", TimeUtil.getTimeDateString("yyyy-MM-dd HH:mm:ss", new Date()));
		List<String> barcodes = new ArrayList<>();
		for (SortInfo sortInfo: this.info.getMails()) {
			barcodes.add(sortInfo.getBarcode());
		}
		//一个面单上扫描出来的单号集合（可能会存在一个面单贴多个条码的情况）
		rp.put("Barcodes", barcodes);
		//员工号
		rp.put("Staff_No", "admin");
		Gson gson = CommonUtil.getGson();
		String content = gson.toJson(rp);
		try
		{
			if (SorterParams.getInstance().isDebugMode()){
				LogUtil.LogError(logger, "upload pack slot error: debug mode doesn't upload data!");
				return false;
			}

			if (CommonUtil.isNull(info.getBoxCode()))
			{
				//双重验证
				LogUtil.LogError(WebPackSlotCmd.logger, "upload pack slot error: pack slot code is Null");
				return false;
			}

			ResultInfo response = WebServiceManager.getInstance().doHttpServiceByPost(
					ServerParam.REMOTE_WEBSERVICE_ADDRESS, remoteMethod, content);
			if (response != null && response.getCode() >= 200 && response.getCode() < 202)
			{
				ret = this.handleResponse(response);
			}
		}
		catch (Exception e)
		{
			LogUtil.LogError(WebPackSlotCmd.logger, "upload pack slot error: " + e);
			ret = false;
		}
		return ret;
	}

	private boolean handleResponse(ResultInfo response)
	{
		boolean ret = false;
		try
		{
			ResultPrint result = CommonUtil.getGson().fromJson(response.getData(), ResultPrint.class);
			switch (result.getCode())
			{
				case 200:
					ret = true;
					info.setTemplate(result.getLabel().getZpl_content());
					SlotManager.getInstance().sendSlotPackInfoToScreen(info.getSlotId(), info.getMails().size(), true);
					break;
				case 403:
					//存在箱号数据，确认是否是重复建包或使用了旧箱号
					LogUtil.LogError(logger, "request  box code  already exists, msg: "+response.getData());
					break;
				default:
					LogUtil.LogError(logger, "request  pack slot failed :  [ " + response.getCode()+" ], msg: "+response.getData());
					break;
			}
		}
		catch (Exception e)
		{
			LogUtil.LogError(WebPackSlotCmd.logger,
					"parse recycle  pack slot result failed : " + e);
		}
		return ret;
	}
}
